/** Class Name: OORTelesalesLeadInteractionLogCtrl
 * Author: Accenture
 * Date: 3-March-2012
 * Requirement/Project Name: OOR Telesales
 * Requirement Description:  
 **/
public class OORTelesalesLeadInteractionLogCtrl
{
    public integer previewClockTime { get; set;}  
    public Boolean renderDispReason { get; set;}
    public Boolean renderSaveBtn { get; set;} 
    public Boolean renderleadAccept { get;set;}      
    public Boolean disableNextBtn { get; set;} 
    public Boolean disableExitBtn { get; set;} 
    public Boolean disableSaveBtn { get; set;} 
    public Boolean errorflg  { get; set;} 
          
    public DateTime currentTimeStamp {get;set;}
    public String errorMsg {get;set;}
    public String recId {get;set;} 
    public String leadName{get;set;} 

    public String ANI { get; set;}
    public String CallObject { get; set;} 
    public Integer CallDurationInSeconds { get; set;} 
    public String CallType { get; set;}  
    public String CallDisposition { get; set;}            
    public String statusMessage { get; set; }
    public Lead mLead { get; set;}
 
    private DateTime callDuration;
    private final Id OOR_TELE_CAMPAIGN_LEAD_QUEUE;
    private final ID LOCAL_ADVERTISER_REC_TYPE_ID;
               
   /**
    *  Constructor 
    *
    */ 
   public OORTelesalesLeadInteractionLogCtrl(ApexPages.StandardController controller) 
   {    
       mLead =  (Lead)controller.getRecord();
       OOR_TELE_CAMPAIGN_LEAD_QUEUE  = OORTelesalesUtility.getQueueID(OORTelesalesTextConstant.OOR_TELE_CAMPAIGN_LEAD_QUEUE);
       LOCAL_ADVERTISER_REC_TYPE_ID = RecordTypeHelper.GetRecordTypeIdByDevName('Lead', OORTelesalesTextConstant.LOCAL_ADVERTISER_LEAD_REC_TYPE);
       initializeTask();
       renderDispReason  = false;
       errorflg   = false;
       disableNextBtn = false;
       disableExitBtn = false;
      
       previewClockTime = 0;
       callDuration = DateTime.now();  
       
       if(mLead.TemporaryOwner__c && mLead.Preview_Clk_Display_Flag__c  )
       {
            disableSaveBtn = true;
            renderleadAccept = true;
       }
       else
       {
           disableSaveBtn = false;
           if(mLead.Lead_Status_ReadOnly__c != OORTelesalesTextConstant.LEAD_IN_PROGRESS_STATUS)
           {
               renderleadAccept = false;
           }
           else
           {
               renderleadAccept = true;
           }
       }
    }   

    public String caseId { 
        get {
            if(caseId == null) {
                caseId = ApexPages.currentPage().getParameters().get('id');
            }
            return caseId;
        }
        set; 
    }

    public void updateWhoWhatId() 
    {
       List<Lead> leadList = [Select id from Lead where id = :caseId];
       if(leadList.size() == 0)
       {
           statusMessage = 'This log is not associated with a lead! Please save the lead.';
           return;       
        }
        task.whoId =  mLead.id;
        task.ANI__c= ANI;
      
    }
    
  /**
    *  initialize new Task object
    *
    */ 
    private void initializeTask() 
    {
        Lead tempLead = null;
        List<Lead> leadList = null;
        
        updateWhoWhatId();
        task.subject = Subject;
        task.Type__c= OORTelesalesTextConstant.INTERACTIVE_CALL_LOG_TYPE;
        leadList = [Select TemporaryOwner__c,Disposition__c,Follow_Up_Date__c,Lead_Notes__c,OORTelesalesCampaign__c from Lead where id=:mLead.Id];
        if(leadList.size() > 0)
        {
            tempLead =   leadList.get(0);
        }
            
        // Check if query has returned any query 
        if( tempLead!=null)
        {
                
            if(tempLead.OORTelesalesCampaign__c!=null && tempLead.TemporaryOwner__c)
            {
                 task.Type__c= OORTelesalesTextConstant.INTERACTIVE_CALL_LOG_TYPE;
            }
            else
            {
                 task.Type__c=OORTelesalesTextConstant.INTERACTIVE_ACTIVITY_LOG_TYPE;
            }
        } 
   }
    
    private String Subject 
    { 
        get {
            Subject = 'Call at ' + DateTime.now();
            
            return Subject;
        }
        set; 
    }

    
   public Task task 
   { 
        get {
            if(task == null) {
                task = new Task();
                if(RecordTypeIDs__c.getInstance().OOR_Telesales_Task_RecordType__c!=null)
                {
                    task.RecordTypeID = RecordTypeIDs__c.getInstance().OOR_Telesales_Task_RecordType__c;
                    task.Status = OORTelesalesTextConstant.TASK_COMPLETED_STATUS;
                }
            }
            return task;
        }
        set; 
    }
 
   /**
    *  Intilize the call data in task Obj
    *
    */
    public void setCallAttachedData() 
    {        
        task.CallObject = CallObject;  
        task.ANI__c = ANI;
    }
   
   /**
    *  Intilize the call Begin data in task Obj
    *
    */         
    public void setCallBeginData()
    {   
       
       disableNextBtn = true;
       disableExitBtn = true;
       if(mLead.TemporaryOwner__c && mLead.Preview_Clk_Display_Flag__c  )
       {       
           disableSaveBtn = true;
       }
        
       task.whoId =  mLead.id;
       task.ANI__c= ANI;
       task.subject = Subject;
       task.StartTime__c = DateTime.now();
       task.Type__c=OORTelesalesTextConstant.INTERACTIVE_CALL_LOG_TYPE;
    }
    
   /**
    *  Intilize the call end data in task Obj
    *
    */
    public void setCallEndData() 
    {
        task.CallDurationInSeconds = CallDurationInSeconds;
        task.CallDisposition = CallDisposition; 
        task.EndTime__c  = DateTime.now();        

        if(mlead.PreviewTime__c != null)
        {
              task.Duration__c  =   mlead.PreviewTime__c -previewClockTime  ;
        }      
        disableNextBtn = true;
        disableExitBtn = true;
        
        if(mLead.TemporaryOwner__c && mLead.Preview_Clk_Display_Flag__c  )
        {
            disableSaveBtn = false;
        }
    }
    
   /**
    *  Save the  task Obj to the database
    *
    */
    public void save() 
    {
    
       Notes__c notes = null;               
       errorflg   = false;
       if(task.Disposition__c  == null || task.Disposition__c  == '' )
       {
           errorflg   = true;
           OORTelesalesUtility.displayErrorMsg(OORTelesalesTextConstant.DISPOSITION_CANNOT_BE_BLANK_ERR_MSG);
           return;
       }
        mLead.Preview_Clk_Display_Flag__c  = false;
       
       renderleadAccept = false;
       disableNextBtn = false;
       disableExitBtn = false;
       task.LeadPhone__c = mLead.Phone;
       task.CallDisposition = task.Disposition__c;       
       task.CampaignName__c= mLead.OORTelesalesCampaign__r.name;
       
        try
        {
            if(!mLead.Preview_Clk_Display_Flag__c && mLead.TemporaryOwner__c)
            {
                update mlead;
            }
            upsert task;
            notes = createNotes(task);
            task = null;
            insert notes;
            initializeTask();
            task.ANI__c= ANI;
            task.CallObject = CallObject;
        
        }
        catch(Exception ex)
        {
            errorflg   = true;
            GeneralConstants.mailAnyExceptionToMe('OORTelesalesLeadInteractionLogCtrl','save',ex);
        }
        statusMessage = 'Last save at ' + DateTime.now();
      
        
    }
   /**
    *  Save the  task Obj to the database
    *
    */
    public void saveAndNew() 
    {
        save();   
    }    
    
    /**
     * Grab Next Lead associated with a Particular Campaign
     *
     */
     public void nextLead()
     {
     
        Set<ID> leadId = new  Set<ID>();
        List<CampaignMember> campMembList = null;
       
        List<Lead> leadList = null;
        Lead randomLead = null;
        
        errorMsg = null;
        recId = null;
        
        try
        {  
            updateLead();
            campMembList=[Select LeadId  from CampaignMember where CampaignId=:mLead.OORTelesalesCampaign__c];
        
            for(CampaignMember  campMemb:campMembList)
            {
                 if(campMemb.LeadId!=null)
                 {
                       leadId.add(campMemb.LeadId);
                 }
            }         
            
            currentTimeStamp=DateTime.Now();
            
            /* get lead assocaited with the campaign  which 
              is in lead status = NEW ,
              temp owner is false,
              owner is queue and 
              campaign timer is < now() or campaign timer is null */
              
            leadList = [Select  name,TemporaryOwner__c,PreviewShow__c,Preview_Clk_Display_Flag__c ,PreviewClock__c,LeadVisitedCounter__c ,CurrentTimeStamp__c,CampaignTimer__c,PreviousOwner__c,OwnerId,OORTelesalesCampaign__c from Lead 
            
            where  Id IN:leadId 
            and OORTelesalesCampaign__c=:mLead.OORTelesalesCampaign__c 
            and Lead_Status_ReadOnly__c= :OORTelesalesTextConstant.LEAD_NEW_STATUS  
            and RecordTypeId=:LOCAL_ADVERTISER_REC_TYPE_ID 
            and ownerID = :OOR_TELE_CAMPAIGN_LEAD_QUEUE 
            and ( CampaignTimer__c = null or    CampaignTimer__c < :System.Now()) Order by Name];
       
            // Check if query has returned any query 
                 
            if(leadList.size()> 0)
            {    
                 // Choose a random Lead from all available.
                 Integer randomInt = OORTelesalesUtility.getRandomInt(leadList.size());
                 randomLead = leadList[randomInt];

                   if(randomLead !=null  ) 
                   {
                      recId=randomLead.Id; 
                      leadName=randomLead.Name; 
                      randomLead.OwnerId = UserInfo.getUserId();
                      randomLead.PreviousOwner__c=UserInfo.getUserId();
                      randomLead.TemporaryOwner__c=True;
                      randomLead.PreviewShow__c=True;
                      randomLead.Preview_Clk_Display_Flag__c = true;
                      update randomLead;     
                          
                  }                           
              }
              else
              {
                errorMsg = OORTelesalesTextConstant.NO_LEAD_FOR_CAMPAIGN_ERR_MSG;
              }
              
       }
       catch(Exception ex)
       {
          GeneralConstants.mailAnyExceptionToMe('OORTelesalesLeadInteractionLogCtrl','nextLead',ex);
       }     
   }
   
   /**
    *  Assign the lead to the loged in user.
    *
    */       
    public void acceptLead()
    {
        errorflg   = false;
        renderleadAccept = true;
        mLead.ownerID = UserInfo.getUserId();
        mLead.Lead_Status_ReadOnly__c = OORTelesalesTextConstant.LEAD_IN_PROGRESS_STATUS;
        mLead.TemporaryOwner__c =false;
        mLead.CampaignAcceptedLeadCounter__c  =  mLead.CampaignAcceptedLeadCounter__c == null ? 1 : mLead.CampaignAcceptedLeadCounter__c +1;
        
        try
        {
            update mLead;
        }
        catch(Exception ex)
        {
            renderleadAccept = false;
            errorflg   = true;
            GeneralConstants.mailAnyExceptionToMe('OORTelesalesLeadInteractionLogCtrl','acceptLead',ex);
        }     
    }
    
   /**
    *   Initilize the Disposition reasons when invalid disposition is  selected 
    *
    */       
    public void initDispReason()
    {
        renderDispReason  = false;
        if(task.Disposition__c !=null  && task.Disposition__c ==  OORTelesalesTextConstant.INVALID_LOG_DISPOSITION)
        {
            renderDispReason = true;    
        }         
    }
    
   /**
    *    Cancel Lead
    *
    */       
    public void cancelLead()
    {
        try
        {
            updateLead();
        }
        catch(Exception e)
        {
             GeneralConstants.mailAnyExceptionToMe('OORTelesalesLeadInteractionLogCtrl','cancelLead',e);
        }       
    }
    
   /**
    *   Update Lead
    *
    */       
    public void updateLead()
    {
         Lead  leagObj = null;
         List<Lead> leadTempLockList = null;
         leadTempLockList = [Select TemporaryOwner__c,LeadVisitedCounter__c ,Skip_Lead_Counter__c, LastCallResult__c,PreviewTime__c ,Preview_Clock_Expired_counter__c,PreviewShow__c,Preview_Clk_Display_Flag__c ,Disposition__c,ownerId,Follow_Up_Date__c,Lead_Notes__c,OORTelesalesCampaign__c from Lead where id=:mLead.Id and Lead_Status_ReadOnly__c= :OORTelesalesTextConstant.LEAD_NEW_STATUS];
            
         // Check if query has returned any query 
         if( leadTempLockList.size()>0)
         {
              leagObj = leadTempLockList.get(0);
              leagObj.TemporaryOwner__c = false;
              leagObj.OwnerId= OOR_TELE_CAMPAIGN_LEAD_QUEUE;
              leagObj.Preview_Clk_Display_Flag__c = False;     
              leagObj.PreviewShow__c=False;         
              leagObj.LeadVisitedCounter__c =  leagObj.LeadVisitedCounter__c == null ? 1 : leagObj.LeadVisitedCounter__c +1;  
                
              // Check if preview Clock has Expired  
              if(previewClockTime != null && previewClockTime <= -1)
              {
                  leagObj.Preview_Clock_Expired_counter__c =  leagObj.Preview_Clock_Expired_counter__c == null ? 1 : leagObj.Preview_Clock_Expired_counter__c +1;
                  createLeadSkipHistory(OORTelesalesTextConstant.LEAD_SKIP_HISTORY_EXPIRE_TYPE,leagObj.PreviewTime__c );  
              }
              // Check lead Last disposition is populated 
              else if(leagObj.LastCallResult__c == null || leagObj.LastCallResult__c == '')
              {
                  leagObj.Skip_Lead_Counter__c = leagObj.Skip_Lead_Counter__c == null ? 1 : leagObj.Skip_Lead_Counter__c +1;  
                  createLeadSkipHistory(OORTelesalesTextConstant.LEAD_SKIP_HISTORY_SKIP_TYPE,leagObj.PreviewTime__c - previewClockTime  );
              }
              // Fire the update to the database 
              update leadTempLockList;
         }             
    } 
    
   /**
    *    Exit Lead
    *
    */       
    public void exitCampaign()
    {
        
        try
        {
            updateLead();
        }
        catch(Exception e)
        {
             GeneralConstants.mailAnyExceptionToMe('OORTelesalesLeadInteractionLogCtrl','exitCampaign',e);
        }       
    }
    
    /**
     *  Creates Lead Skip History  When Lead is Skiped.
     *
     */
    private void createLeadSkipHistory(String historyType , Decimal previewClock)
    {
        LeadSkipHistory__c leadHistory = new LeadSkipHistory__c();
        leadHistory.Type__c = historyType;
        leadHistory.Time__c  = Datetime.now();
        leadHistory.Preview_Time__c = previewClock;
        leadHistory.LeadId__c = mLead.Id;
        leadHistory.Campaign__c = mLead.OORTelesalesCampaign__c;
        insert leadHistory; 
        
    }
    
    /**
     *  Creates  Notes record when Task is created.  
     *
     */
     private Notes__c createNotes(Task taskObj)
     {
   //     final ID oorNotesRecTypeID = RecordTypeHelper.GetRecordTypeIdByDevName('Notes__c', OORTelesalesTextConstant.OOR_NOTES_REC_TYPE);
        Notes__c notes = new Notes__c();       
        notes.StartTime__c =  task.StartTime__c;
        notes.Disposition__c = task.Disposition__c;
        notes.EndTime__c = task.EndTime__c ;
        notes.Description__c = task.Description;
        notes.Lead__c = task.whoId ;
        notes.Note_Type__c = task.Type__c;
        notes.CallDurationInSeconds__c      =  task.CallDurationInSeconds ;
        notes.Subject__c  = task.subject;
        notes.Telesales__c = true;
        notes.Preview_Time_seconds__c  =  task.Duration__c;
        //notes.recordTypeId  =oorNotesRecTypeID;
        notes.LeadPhone__c  = task.LeadPhone__c ;
        notes.Campaign__c=   mLead.OORTelesalesCampaign__c;
        return notes;
    }
}